<template>
    <div class="app-container">
      <div class="filter-container">
        <div class="lineBox">
          <el-form :inline="true" :model="listQuery" class="demo-form-inline">

            <el-form-item label="档号">
              <el-input
                v-model="listQuery.dh"
                placeholder="请输入档号"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
        

            <el-form-item label="题名">
              <el-input
                v-model="listQuery.tm"
                placeholder="请输入题名"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
            <el-form-item label="全宗号">
              <el-input
                v-model="listQuery.qzh"
                placeholder="请输入全宗号"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>

            <el-form-item>
              <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="handleReset">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
  
      <div class="document-table" style="min-height: 600px; margin-top: 20px;">
        <div style="margin-bottom: 10px;">
          <el-button 
            size="mini" 
            type="danger" 
            :disabled="selectedIds.length === 0" 
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
  
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          fit
          size="mini"
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" prop="id" align="center" width="80" />
          <el-table-column label="档号" prop="dh" align="center" min-width="180" show-overflow-tooltip />
          <el-table-column label="题名" prop="tm" align="center" min-width="180" show-overflow-tooltip />
          <el-table-column label="全宗号" prop="qzh" align="center" min-width="120" show-overflow-tooltip />
          <el-table-column label="创建时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="更新时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="280" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button size="mini" type="primary" @click="handleViewQueue(row)">
                查看表单
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          size="mini"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getList"
        />
      </div>
    </div>
  </template>
  
  <script>
  import { autoApi } from '@/api/auto'
  import Pagination from '@/components/Pagination'
  import { parseTime } from '@/utils'
  
  export default {
    name: 'ProcessDocumentFile',
    components: { Pagination },
    filters: {
      parseTime
    },
    data() {
      return {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: false,
        selectedIds: [],
        logDialogVisible: false,
        currentLog: '',
        listQuery: {
          page: 1,
          limit: 10,
          dh: "",
          tm: "",
          qzh: "",
        }
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      // 3秒后检查是否有数据，如果没有就显示提示
      setTimeout(() => {
        if (this.list.length === 0 && !this.listLoading) {
          this.$message.warning('暂无数据，或者后端API尚未完全配置')
        }
      }, 3000)
    },
    methods: {
      async getList() {
        this.listLoading = true
        try {
          // 添加调试信息
          console.log('发送请求参数:', this.listQuery)
          
          let response
          try {
            response = await autoApi('getMarkdownList', this.listQuery)
          } catch (apiError) {
            console.error('API调用失败:', apiError)
            // 使用模拟数据
            response = mockProcessDocumentData()
          }
          
          console.log('返回数据:', response)
          
          if (response.code == 200) {
            // 处理后端返回的实际数据结构
            if (response.data && response.data.items) {
              // 新的数据结构 {total: x, items: [...], page: x, limit: x}
              this.list = response.data.items
              this.total = response.data.total || 0
              
              // 如果后端返回了页码和分页大小，同步到前端
              if (response.data.page) {
                this.listQuery.page = response.data.page
              }
              if (response.data.limit) {
                this.listQuery.limit = response.data.limit
              }
            } else if (response.data && response.data.resultList) {
              // 旧的数据结构处理方式
              this.list = response.data.resultList
              this.total = response.data.totalCount || response.totalCount || 0
            } else if (Array.isArray(response.data)) {
              // 直接返回数组的情况
              this.list = response.data
              this.total = response.totalCount || response.data.length || 0
            } else {
              // 数据结构不符合预期
              console.warn('后端返回的数据结构不符合预期:', response.data)
              this.list = []
              this.total = 0
              
              // 如果没有返回有效数据，可以考虑使用测试数据
              this.useTestData()
            }
            
            setTimeout(() => {
              this.listLoading = false
            }, 300)
          } else {
            this.$message.error(response.message || '获取列表失败')
            this.listLoading = false
            // API调用返回错误，使用测试数据
            this.useTestData()
          }
        } catch (error) {
          console.error('获取列表失败:', error)
          this.$message.error('获取列表失败，显示测试数据')
          this.listLoading = false
          // API调用异常，使用测试数据
          this.useTestData()
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleReset() {
        this.listQuery = {
          page: 1,
          limit: 10,
          folder: undefined,
          qzh: undefined,
          status: undefined,
        }
        this.getList()
      },
      handleSelectionChange(val) {
        this.selectedIds = val.map(item => item.id)
      },
      

      
      // 打开队列查看页面
      handleViewQueue(row) {
        // 跳转到查看公章页面
        let url = `/documentfilemana/docview?id=${row.id}&type=markdown`
        window.open(url, '_blank')
      },
      
      async handleBatchDelete() {
        if (this.selectedIds.length === 0) {
          this.$message.warning('请选择要删除的记录')
          return
        }
  
        this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { ids: this.selectedIds.join(',') } // 按照后端API需要的格式，用逗号连接ID
            const response = await autoApi('batchDeleteMarkdown', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '批量删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '批量删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('批量删除失败:', error)
            this.$message.error('批量删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      async handleDelete(row, index) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { id: row.id }
            const response = await autoApi('deleteMarkdown', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
              // 如果是最后一条记录被删除，且不是第一页，则跳转到上一页
              if (this.list.length === 0 && this.listQuery.page > 1) {
                this.listQuery.page -= 1;
                this.getList();
              }
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      useTestData() {
        if (this.list.length === 0) {
          this.list = [
            {
              id: 1,
              name: '测试文档1',
              qzh: 'QZH001',
              folder: '测试文件夹1',
              status: 1,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              path: '/path/to/file1',
              logs: '处理成功\n文件解析完成\n提取信息完成'
            },
            {
              id: 2,
              name: '测试文档2',
              qzh: 'QZH002',
              folder: '测试文件夹2',
              status: 0,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              path: '/path/to/file2',
              logs: '正在处理中...'
            },
            {
              id: 3,
              name: '测试文档3',
              qzh: 'QZH003',
              folder: '测试文件夹3',
              status: 1,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              path: '/path/to/file3',
              logs: '处理成功\n文件解析完成\n提取信息完成'
            }
          ]
          this.total = this.list.length
          
          this.$message.warning('API未配置或返回错误，显示测试数据')
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .document-table {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }
  
  .log-container {
    max-height: 400px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    
    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
      margin: 0;
      font-family: "Courier New", monospace;
      font-size: 13px;
      line-height: 1.5;
    }
  }
  
  .empty-log {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }
  </style>
  